<template>
  <div class="login-page">
    <div class="left"></div>
    <div class="login">
      <h1>红烧蹄髈好吃</h1>
      <el-form
        :model="loginForm"
        status-icon
        :rules="rules"
        ref="loginForm"
        label-width="100px"
        class="demo-loginForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            @keydown.Enter="alert('哈哈哈')"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <video
      class="liu"
      muted
      autoplay
      loop
      src="../../assets/video/bg_video.mp4"
      preload="auto"
    ></video>
  </div>
</template>

<script>
//登入逻辑的实现
//1.收集用户输入的username&password传递给后端

//2.登入通过后，将后端返回的token存到本地，跳转到主页
//3.每次请求的时候，携带token到请求头authorization

//4.展示token校验正确的数据

//5.校验不通过，跳转到登入页
import { mapMutations} from "vuex"
import { login } from "@/api";
export default {
  data() {
    //jsDoc的注释方式
    /**
     * @param {Object} rule 就是一个表单验证对象
     * @param {String} value 输入值
     * @param {Function} callback 校验通过不传参 不通过传参
     */
    var validateUsername = (rule, value, callback) => {
      //用户名正则，4到16位（字母，数字，下划线，减号）
      // var uPattern = /^[a-zA-Z0-9_-]{4,16}$/;
      // if(!uPattern.test(value)){
      //   callback("4到16位（字母，数字，下划线，减号）")
      // }else{
      //   callback()
      // }
      if (!value) {
        callback("4到16位（字母，数字，下划线，减号）");
      } else {
        callback();
      }
    };
    var validatePassword = (rule, value, callback) => {
      if (!value) {
        callback("请输入密码");
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapMutations(["SET_USERINFO"]),
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {//本地校验通过
          //打开登入加载动画
          const loading = this.$loading({
            lock: true,
            text: "诶嘿！慢悠悠的登陆，你急不急！",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });

          let { username, password } = this.loginForm;
          //放松登入请求
          login(username, password)
            .then((res) => {

              console.log(res);

              //服务器响应，关闭loading
              loading.close();
              if (res.data.state) {
                //用户名密码正确
                localStorage.setItem("crlm-token", res.data.token);
                localStorage.setItem("crlm-userinfo", JSON.stringify(res.data.userInfo) );
                //更改vuex中state的[userInfo]的值
                this.SET_USERINFO(res.data.userInfo)
                //跳转到主页
                this.$router.push("/Welcome");
                this.$message.success('登陆成功');
              } else {
                //用户名密码错误
                this.$message.error('用户名密码错误');
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style scoped>
.login-page {
  width: 100%;
  height: 100%;
  /* background: url("../../assets/imgs/bg.jpg"); */
  background: url("../../assets/imgs/dl.jpg") no-repeat 0 0 / cover;
  overflow: hidden;
}
/* 表单样式 */
.login {
  z-index: 9;
  width: 25rem;
  height: 30.47619048rem;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 11px;
  text-align: center;
  background: rgba(0, 0, 0, 0.2);
}
h1 {
  color: #fff;
  margin-top: 100px;
  margin-bottom: 50px;
}
.el-button.el-button--primary {
  width: 100%;
  background: linear-gradient(90deg, #1596fb, #002dff);
}
.liu {
  opacity: 0.3;
}
/* .left{
  width: 50%;
  height: 100%;
  background-image: url("../../assets/imgs/tn.png");
  background-repeat: no-repeat;
  background-size: 50%;
  position: absolute;
  opacity: 0.7;
  background-position: 60% 65%;
} */
.el-form.demo-loginForm {
  padding: 0 50px 0 0;
}
</style>